<template>
  <div class="users-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名/昵称/邮箱"
              prefix-icon="Search"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </div>
      </template>

      <!-- 用户列表 -->
      <el-table
        :data="userList"
        style="width: 100%"
        v-loading="loading"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="scope">
            <div class="user-info">
              <el-avatar :size="32" :src="scope.row.avatar"></el-avatar>
              <div class="user-details">
                <div class="username">{{ scope.row.username }}</div>
                <div class="email">{{ scope.row.email }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120" />
        <el-table-column prop="registerTime" label="注册时间" width="150" />
        <el-table-column prop="lastLoginTime" label="最近登录" width="150" />
        <el-table-column prop="postCount" label="发帖数" width="100" />
        <el-table-column prop="commentCount" label="评论数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === '正常'"
              type="danger" 
              size="small" 
              @click="blockUser(scope.row)"
            >
              封禁
            </el-button>
            <el-button 
              v-else
              type="success" 
              size="small" 
              @click="unblockUser(scope.row)"
            >
              解除封禁
            </el-button>
            <el-button type="primary" size="small" @click="viewUserDetails(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog v-model="dialogVisible" title="用户详情" width="60%">
      <div v-if="currentUser" class="user-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="用户ID">{{ currentUser.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ currentUser.username }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ currentUser.nickname }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ currentUser.email }}</el-descriptions-item>
          <el-descriptions-item label="注册时间">{{ currentUser.registerTime }}</el-descriptions-item>
          <el-descriptions-item label="最近登录">{{ currentUser.lastLoginTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="currentUser.status === '正常' ? 'success' : 'danger'">
              {{ currentUser.status }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="发帖数">{{ currentUser.postCount }}</el-descriptions-item>
          <el-descriptions-item label="评论数">{{ currentUser.commentCount }}</el-descriptions-item>
        </el-descriptions>

        <!-- 操作按钮 -->
        <div class="detail-actions">
          <el-button 
            v-if="currentUser.status === '正常'"
            type="danger" 
            @click="blockUser(currentUser, true)"
          >
            封禁用户
          </el-button>
          <el-button 
            v-else
            type="success" 
            @click="unblockUser(currentUser, true)"
          >
            解除封禁
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 封禁确认对话框 -->
    <el-dialog v-model="blockDialogVisible" title="封禁用户" width="30%">
      <div class="block-form">
        <p>确定要封禁用户 "{{ selectedUser?.username }}" 吗？</p>
        <el-form :model="blockForm">
          <el-form-item label="封禁原因" required>
            <el-input v-model="blockForm.reason" type="textarea" rows="3" placeholder="请输入封禁原因"></el-input>
          </el-form-item>
          <el-form-item label="封禁时长">
            <el-select v-model="blockForm.duration" placeholder="请选择封禁时长">
              <el-option label="1天" value="1" />
              <el-option label="3天" value="3" />
              <el-option label="7天" value="7" />
              <el-option label="30天" value="30" />
              <el-option label="永久" value="-1" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="blockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBlock">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 搜索、分页状态
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const userList = ref([])

// 用户详情与操作
const dialogVisible = ref(false)
const currentUser = ref(null)

// 封禁相关状态
const blockDialogVisible = ref(false)
const selectedUser = ref(null)
const blockForm = reactive({
  reason: '',
  duration: '',
})

// 初始化加载
onMounted(() => {
  fetchUsers()
})

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const res = await axios.get('/user/list', {
      params: {
        keyword: searchKeyword.value,
        page: currentPage.value,
        size: pageSize.value,
      }
    })
    userList.value = res.data.data
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUsers()
}

// 分页操作
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

// 查看详情
const viewUserDetails = async (user) => {
  try {
    const res = await axios.get(`/user/detail/${user.id}`)
    currentUser.value = res.data
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取用户详情失败')
  }
}

// 封禁用户（列表 or 详情页中）
const blockUser = (user, fromDetail = false) => {
  selectedUser.value = user
  blockForm.reason = ''
  blockForm.duration = ''
  blockDialogVisible.value = true
  if (fromDetail) {
    dialogVisible.value = false
  }
}

// 解除封禁
const unblockUser = async (user, fromDetail = false) => {
  try {
    await axios.post(`/user/unblock/${user.id}`)
    ElMessage.success('用户已解除封禁')
    if (fromDetail) {
      viewUserDetails(user)
    } else {
      fetchUsers()
    }
  } catch (error) {
    ElMessage.error('解除封禁失败')
  }
}

// 确认封禁
const confirmBlock = async () => {
  if (!blockForm.reason || !blockForm.duration) {
    ElMessage.warning('请填写封禁原因和时长')
    return
  }
  try {
    await axios.post('/user/block', {
      userId: selectedUser.value.id,
      reason: blockForm.reason,
      duration: blockForm.duration,
    })
    ElMessage.success('用户已封禁')
    blockDialogVisible.value = false
    fetchUsers()
  } catch (error) {
    ElMessage.error('封禁失败')
  }
}
</script>

<style scoped>
.users-container {
  padding: 0 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.email {
  font-size: 12px;
  color: #909399;
}

.detail-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.block-form {
  margin-bottom: 20px;
}
</style> 